package com.justech.eat.controller;

import com.justech.common.util.DateUtil;
import com.justech.eat.service.daemons.AutoSubmitOrderService;
import com.justech.eat.service.daemons.OrderSettler;
import com.justech.eat.service.daemons.SysUserSynchronizer;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Date;
import java.util.concurrent.locks.Lock;

/**
 * @program: eat-service
 * @description: 定时任务
 * @author: feifei.li
 * @create: 2020-06-10 10:28
 **/
@RestController
@RequestMapping(value = "daemon/")
public class ScheduledTaskController {

    @Autowired
    SysUserSynchronizer sysUserSynchronizer;

    @Autowired
    AutoSubmitOrderService autoSubmitOrderService;

    @Autowired
    OrderSettler orderSettler;

    @Autowired
    Lock lock;

    @ApiOperation("同步用户信息")
    @Scheduled(cron = "0 0 17 * * ?")
    @GetMapping("user")
    public void synchronizeUsers() {
        lock.tryLock();
        sysUserSynchronizer.synchronization();
        lock.unlock();
    }

    @ApiOperation("自动报餐")
    @Scheduled(cron = "0 0 09 * * ?")
    @GetMapping("autoSubmit")
    public void autoSubmit(String date) {
        lock.tryLock();
        autoSubmitOrderService.startSubmitOrder(date);
        System.out.println("报餐结束");
        lock.unlock();
    }

    @ApiOperation("用餐情况结算")
    @Scheduled(cron = "0 0 07 * * ?")
    @GetMapping("settlement")
    public void settlement(String day) {
        lock.tryLock();
        orderSettler.settle(StringUtils.isNotBlank(day) ? day : DateUtil.dateToShortDate(new Date()));
        lock.unlock();
    }
}
